package com.cht.commonUtil.mail;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.cht.commonUtil.webInit.SP;
import com.cht.commonUtil.widgets.Widgets;

public class UpdateRoleMailMapping extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request,response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding( SP.UIcodeSet );
		response.setContentType("application/json");
		response.setCharacterEncoding( SP.UIcodeSet );
		
		int systemId = Integer.parseInt( request.getParameter("systemId") );
		String subsysId = request.getParameter("subsysId");
		int mailId = Integer.parseInt( request.getParameter("mailId") );
		int recipientTypeId = Integer.parseInt( request.getParameter("recipientTypeId") );
		String roleId = request.getParameter("roleId");					
		String creatorId = request.getParameter("creatorId");			//進行這次異動的當事人
		String addOrDelete = request.getParameter("addOrDelete");
		
		String sql = "";
		String res = "";
		
		Connection conn = null;
		PreparedStatement ps = null;
		
		try {
			conn = Widgets.getConn();
			
			if ( "add".equalsIgnoreCase( addOrDelete ) ) {
				sql = "INSERT INTO mpmailtyperolesubsyssystem (subsysId,mailTypeId,roleId,systemId,recipientTypeId,creatorId,cDT) VALUES (?,?,?,?,?,?,?)";
			} else {
				sql = "DELETE FROM mpmailtyperolesubsyssystem WHERE subsysId=? AND mailTypeId=? AND roleId=? AND systemId=? AND recipientTypeId=?";
			}
			ps = conn.prepareStatement(sql);
			int i=1;
			ps.setString(i++, subsysId);
			ps.setInt(i++, mailId);
			ps.setString(i++, roleId);
			ps.setInt(i++, systemId);
			ps.setInt(i++, recipientTypeId);
			
			if ( "add".equalsIgnoreCase( addOrDelete ) ) {
				ps.setString(i++, creatorId);
				ps.setTimestamp(i++, Widgets.cDT());
			}
			ps.execute();
		} catch (Exception e) {
			res = Widgets.errLog(e);
		} finally {
			try {
				if ( ps !=null ) {ps.close();}
				if ( conn !=null ) {conn.close();}	
			} catch (Exception e) { e.printStackTrace(); };
			
		}
		response.getWriter().write(res);
	}

}
